package com.geekjob1120.geekjob1120pay.support;

import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Locale;

@Component
public class MoneyFormatter implements Formatter<Money> {
    @Override
    public Money parse(String text, Locale locale) throws ParseException {
        if (org.apache.commons.lang3.math.NumberUtils.isParsable(text)){
            return Money.of(CurrencyUnit.of("CNY"), org.apache.commons.lang3.math.NumberUtils.createBigDecimal(text));
        }
        else if(org.apache.commons.lang3.StringUtils.isNoneEmpty(text)){
            String[] src = org.apache.commons.lang3.StringUtils.split(text,' ');
            if(src!=null && src.length == 2 && org.apache.commons.lang3.math.NumberUtils.isParsable(src[1])){
                return Money.of(CurrencyUnit.of(src[0]),org.apache.commons.lang3.math.NumberUtils.createBigDecimal(src[1]));
            }
        }
        throw new ParseException(text + "无法解析为Money对象",0);
    }

    @Override
    public String print(Money object, Locale locale) {
        if (object == null){
            return null;
        }
        return object.getCurrencyUnit().getCode() + " " + object.getAmount();
    }
}
